from functools import wraps

from flask import session, redirect, url_for, abort

from models import User, Permission


# 登陆限制装饰器
def login_limit(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if session.get('user_id'):
            return func(*args, **kwargs)
        else:
            return redirect(url_for('login'))

    return wrapper


# 责任编辑权限限制
def permission_required_for_responsibility(permission):
    def decorator(func):
        @wraps(func)
        def decorated_function(*args, **kwargs):
            user = User.query.filter(User.id == session['user_id']).first()
            if not user.can(permission):
                abort(403)
            return func(*args, **kwargs)
        return decorated_function
    return decorator


# 管理员权限限制
def permission_required_for_administrator(f):
    return permission_required_for_responsibility(Permission.ADMINISTER)(f)
